#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/5/26  15:55
# @Author: 余浪人
# @email: yulangren520@gmail.com


from functools import wraps
from flask import request, jsonify, g
from itsdangerous import SignatureExpired, BadSignature, TimedJSONWebSignatureSerializer
from apps import setting


def generate_token(id, expiration=setting.Config.EXPIRATION):
    s = TimedJSONWebSignatureSerializer(setting.Config.SECRET_KEY, expires_in=expiration)
    return s.dumps({'token': id}).decode('ascii')  # 返回一个token


# 验证to_kent
def verify_token(token_obj):
    @wraps(token_obj)
    def inner(*args, **kwargs):
        from apps.models.system_model import API_Modle
        token = request.json.get('token') if request.is_json else request.args.get('token')  # 允许json 或者 GET
        if token:
            s = TimedJSONWebSignatureSerializer(setting.Config.SECRET_KEY)
            try:
                data = s.loads(token)
            except SignatureExpired:
                return jsonify({"status": 1, "message": "token值过期"})
            except BadSignature:
                return jsonify({"status": 2, "message": "token值无效"})
            if not API_Modle.query.filter(API_Modle.api_ak=="token:"+token).count():
                return jsonify({"status": 3, "message": "key已更新,重新生成"})
            g.uid = data.get('token')  # 获取值
            res = token_obj(*args, **kwargs)
            return res
        else:
            return jsonify({"status": 4, "message": "token值不存在"})

    return inner
